package top.kaoshanji.ch02;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.file.*;

/**
 * 代码清单 ch02-03：WatchService示例(2.4.5节、文件修改通知)
 * author kaoshanji
 * ^_^
 * create time 2024/12/13 16:46
 */
public class WatchServiceDemo {

    private static final Logger logger = LogManager.getLogger(WatchServiceDemo.class);

    private static boolean shutdown = false;

    public static void main(String[] args) {
        logger.info("...代码清单 ch02-03：WatchService示例(2.4.5节、文件修改通知)...");

        try {
            WatchService watcher = FileSystems.getDefault().newWatchService();

            Path dir = FileSystems.getDefault().getPath("D:\\works\\workspace");

            // 监测变化...将该目录登记到变化检测名单中
            WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);

            // 检查 shutdown 标志
            while (!shutdown) {
                // 得到下一个 key 及其事件
                key = watcher.take();
                for (WatchEvent<?> event: key.pollEvents()) {
                    // 检查是否为变化事件
                    if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                        System.out.println("Home dir changed!");
                    }
                }
                // 重置检测 key
                key.reset();
            }

        } catch (IOException | InterruptedException e) {
            System.out.println(e.getMessage());
        }

    }

}
